package com.itheima.service.impl;

import com.itheima.mapper.PrejectMapper;
import com.itheima.mapper.SysUserMapper;
import com.itheima.pojo.jo.UserDataStatisticsJo;
import com.itheima.pojo.po.VisualizationPo;
import com.itheima.service.IVisualizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class IVisualizationServiceImpl implements IVisualizationService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PrejectMapper prejectMapper;



    /**
     * 获取用户数据列表
     * @param po
     * @return
     */
    @Override
    public Map<String, Object> getUserDataList(VisualizationPo po) {
        Map<String, Object> result = new HashMap<>();
        List<LocalDateTime> time = (List<LocalDateTime>) getTime(po,false);
        // 计算时间间隔有多少天
        int days = (int) time.get(1).toLocalDate().toEpochDay() - (int) time.get(0).toLocalDate().toEpochDay();
        for (int i = 0; i < 3; i++){
            Map<String, Object> adminMap = new HashMap<>();
            UserDataStatisticsJo jo = new UserDataStatisticsJo();
            adminMap = sysUserMapper.getUserDataAccountList(time.get(0), time.get(1), i);
            jo.setTotalCount(Integer.parseInt(adminMap.get("totalCount").toString()));
            jo.setNewCount(Integer.parseInt(adminMap.get("newCount").toString()));
            Map<String, Object> adminMap1 = new HashMap<>();
            adminMap1 = sysUserMapper.getUserDataTokenList(time.get(0), time.get(1), i);
            int anInt = Integer.parseInt(adminMap1.get("loginCount").toString());
            jo.setLoginCount(anInt);
            jo.setActiveCount(anInt==0?0: anInt/days);
            result.put(i==0?"student":i==1?"teacher":"admin", jo);
        }
        return result;
    }

    /**
     * 获取用户地图数据列表
     * @param po
     * @return
     */
    @Override
    public List<Map<String, Object>> getUserMapDataList(VisualizationPo po) {
        // 省份 数据
        List<String> chinaData = getMapChinaData();
        List<Map<String, Object>> result = new ArrayList<>();
        List<LocalDateTime> time = (List<LocalDateTime>) getTime(po,false);
        // 循环遍历省份
        result = sysUserMapper.getUserMapData(chinaData, time.get(0), time.get(1));
        return result;
    }

    /**
     * 获取用户统计数据
     * @param po
     * @return
     */
    @Override
    public List<Integer> userDataStatistics(VisualizationPo po) {
        List<Integer> result = new ArrayList<>();
        List<LocalDateTime> time = (List<LocalDateTime>) getTime(po,false);
        for (int i = 2; i >=0; i--) {
            result.add(sysUserMapper.getUserDataStatistics(time.get(0), time.get(1), i));
        }
        return result;
    }

    /**
     * 获取用户登录统计数据
     * @param po
     * @return
     */
    @Override
    public List<Map<String, Object>> userLoginStatistics(VisualizationPo po) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<LocalDateTime> time = (List<LocalDateTime>) getTime(po,false);
        for (int i = 0; i < 3; i++) {
            Map<String, Object> dateMap = new HashMap<>();
            dateMap.put("name",i==0?"学生": i==1?"教师": "管理员");
            dateMap.put("value", sysUserMapper.getUserActiveStatistics(time.get(0), time.get(1), i));
            result.add(dateMap);
        }
        return result;
    }

    /**
     * 获取用户活跃统计数据
     * @param po
     * @return
     */
    @Override
    public List<Map<String, Object>> userActiveStatistics(VisualizationPo po) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<LocalDateTime> time = (List<LocalDateTime>) getTime(po,false);
        for (int i = 0; i < 4; i++) {
            Map<String, Object> dateMap = new HashMap<>();
            dateMap.put("name",i==0?"学生": i==1?"教师": i==2?"管理员": "其他");
            dateMap.put("value", sysUserMapper.getUserActiveStatistics(time.get(0), time.get(1), i));
            result.add(dateMap);
        }
        return result;
    }
    // 获取开始时间和结束时间
    public Object getTime(VisualizationPo po,boolean isDate){
        List<LocalDateTime> timeList = new ArrayList<>();
        List<String> dateList = new ArrayList<>();
        if (po.getType().equals("day")){
            timeList.add(LocalDateTime.parse(po.getStartTime()+" 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            timeList.add(LocalDateTime.parse(po.getEndTime()+" 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            if (isDate){
                LocalDate startDate = LocalDate.parse(po.getStartTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                LocalDate endDate = LocalDate.parse(po.getEndTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                while (startDate.isBefore(endDate)) {
                    dateList.add(startDate.toString());
                    startDate = startDate.plusDays(1);
                }
                dateList.add(endDate.toString());
                return dateList;
            }
        }
        else if (po.getType().equals("month")){
            LocalDateTime parse = LocalDateTime.parse(po.getStartTime()+ "-01 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            timeList.add(parse);
            LocalDateTime endDay = LocalDateTime.parse(po.getEndTime() + "-01 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                    .with(TemporalAdjusters.lastDayOfMonth());
            endDay = endDay.withHour(23).withMinute(59).withSecond(59);
            timeList.add(endDay);
            if (isDate){
                LocalDate startDate = LocalDate.parse(parse.toString().substring(0,10), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                LocalDate endDate = LocalDate.parse(po.getEndTime()+"-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                while (startDate.isBefore(endDate)) {
                    dateList.add(startDate.getYear()+"-"+String.format("%02d", startDate.getMonthValue()));
                    startDate = startDate.plusMonths(1);
                }
                dateList.add(endDate.getYear()+"-"+String.format("%02d", endDate.getMonthValue()));
                return dateList;
            }
        }
        else if (po.getType().equals("year")){
            LocalDateTime parse = LocalDateTime.parse(po.getStartTime() + "-01-01 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            timeList.add(parse);
            timeList.add(LocalDateTime.parse(po.getStartTime() + "-12-31 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            if (isDate){
                LocalDate startDate = LocalDate.parse(parse.toString().substring(0,10), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                LocalDate endDate = LocalDate.parse(po.getStartTime()+ "-12-31", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                while (startDate.isBefore(endDate)) {
                    dateList.add(startDate.getYear()+"-"+String.format("%02d", startDate.getMonthValue()));
                    startDate = startDate.plusMonths(1);
                }
                dateList.add(endDate.getYear()+"-"+String.format("%02d", endDate.getMonthValue()));
                return dateList;
            }
        }
        return timeList;
    }

    private List<String> getMapChinaData(){
        List<String> provinceList = List.of("澳门","香港","台湾","新疆","宁夏","青海","甘肃","陕西","西藏","云南",
                "贵州","四川", "重庆","海南","广西","广东","湖南","湖北","河南","山东","江西", "福建","安徽","浙江","江苏","上海",
                "黑龙江","吉林","辽宁","内蒙古","山西","河北","天津","北京");
        return provinceList;
    }

    /**
     * 获取项目数据列表
     * @param po
     * @return
     */
    @Override
    public Map<String, Object> projectStatistics(VisualizationPo po) {
        Map<String, Object> result = new HashMap<>();
        List<LocalDateTime> time = (List<LocalDateTime>) getTime(po,false);
        // 项目数据
        Map<String, String> adminMap = new HashMap<>();
        UserDataStatisticsJo jo1 = new UserDataStatisticsJo();
        adminMap = prejectMapper.projectLineData(time.get(0), time.get(1));
        jo1.setTotalCount(Integer.parseInt(String.valueOf(adminMap.get("totalProject"))));
        jo1.setNewCount(Integer.parseInt(String.valueOf(adminMap.get("newProject"))));
        Map<String, Long> map = new HashMap<>();
        map = prejectMapper.getProjectVisit(time.get(0), time.get(1));
        jo1.setLoginCount(Integer.parseInt(String.valueOf(map.get("count"))));
        jo1.setActiveCount(Integer.parseInt(String.valueOf(map.get("visit"))));
        result.put("project", jo1);
        // 项目进度统计
        Map<String, Object> projectProgress = new HashMap<>();
        UserDataStatisticsJo jo = new UserDataStatisticsJo();
        projectProgress = prejectMapper.getProjectProgress(time.get(0), time.get(1));
        jo.setTotalCount(Integer.parseInt(String.valueOf(projectProgress.get("totalCount"))));
        jo.setNewCount(Integer.parseInt(String.valueOf(projectProgress.get("newCount"))));
        jo.setLoginCount(Integer.parseInt(String.valueOf(projectProgress.get("loginCount"))));
        jo.setActiveCount(Integer.parseInt(String.valueOf(projectProgress.get("activeCount"))));
        result.put("projectProgress", jo);
        return result;
    }

    /**
     * 获取项目折线图数据
     * @param po
     * @return
     */
    @Override
    public Map<String, Object> projectLineData(VisualizationPo po) {
        Map<String, Object> result = new HashMap<>();
        List<String> time = (List<String>) getTime(po, true);
        result.put("dateList",time);
        // 新增项目
        List<Integer> newProject = new ArrayList<>();
        // 项目总数
        List<Integer> totalProject = new ArrayList<>();
        // 项目占比
        List<Integer> projectRate = new ArrayList<>();
        if (po.getType().equals("day")){
            for (int i = 0; i < time.size(); i++) {
                Map<String,String> map = new HashMap<>();
                LocalDateTime startTime = LocalDateTime.parse(time.get(i)+" 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                LocalDateTime endTime = LocalDateTime.parse(time.get(i)+" 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                map = prejectMapper.projectLineData(startTime, endTime);
                newProject.add(Integer.parseInt(String.valueOf(map.get("newProject"))));
                totalProject.add(Integer.parseInt(String.valueOf(map.get("totalProject"))));
                projectRate.add(totalProject.get(i)==0?0:newProject.get(i)*100/totalProject.get(i));
            }
        }else {
            for (int i = 0; i < time.size(); i++) {
                Map<String,String> map = new HashMap<>();
                LocalDateTime startTime = LocalDateTime.parse(time.get(i)+"-01 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                LocalDate endDate = LocalDate.parse(time.get(i)+"-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                LocalDateTime endTime = LocalDateTime.parse(endDate.with(TemporalAdjusters.lastDayOfMonth())+" 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                map = prejectMapper.projectLineData(startTime, endTime);
                newProject.add(Integer.parseInt(String.valueOf(map.get("newProject"))));
                totalProject.add(Integer.parseInt(String.valueOf(map.get("totalProject"))));
                projectRate.add(totalProject.get(i)==0?0:newProject.get(i)*100/totalProject.get(i));
            }
        }
        result.put("newProject",newProject);
        result.put("totalProject",totalProject);
        result.put("projectRate",projectRate);
        return result;
    }

    /**
     * 获取项目地图数据
     * @param po
     * @return
     */
    @Override
    public List<Map<String, Object>> projectMapData(VisualizationPo po) {
        // 省份 数据
        List<String> chinaData = getMapChinaData();
        List<Map<String, Object>> result = new ArrayList<>();
        List<LocalDateTime> time = (List<LocalDateTime>) getTime(po,false);
        for (String datum : chinaData) {
            Map<String, Object> provinceMap = new HashMap<>();
            provinceMap.put("name", datum);
            provinceMap.put("value", prejectMapper.getProjectMapData(datum, time.get(0), time.get(1)));
            result.add(provinceMap);
        }
        return result;
    }

    /**
     * 获取项目类型饼图数据
     * @param po
     * @return
     */
    @Override
    public List<Integer> getProjectTypePie(VisualizationPo po) {
        List<Integer> result = new ArrayList<>();
        List<LocalDateTime> time = (List<LocalDateTime>) getTime(po,false);
        for (int i = 0; i < 4; i++) {
            result.add(prejectMapper.getProjectTypePie(time.get(0), time.get(1), i));
        }
        return result;
    }

    /**
     * 获取项目类型柱状图数据
     * @param po
     * @return
     */
    @Override
    public List<Map<String, Object>> getProjectTypeBar(VisualizationPo po) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<LocalDateTime> time = (List<LocalDateTime>) getTime(po, false);
        for (int i = 0; i < 3; i++) {
            Map<String, Object> mapData = new HashMap<>();
            mapData.put("name", i == 0 ? "学生" : i == 1 ? "教师" : "管理员");
            mapData.put("value", prejectMapper.getProjectTypeBar(time.get(0), time.get(1), i));
            result.add(mapData);
        }
        return result;
    }

    /**
     * 获取项目访问量数据
     * @param po
     * @return
     */
    @Override
    public Map<String, Object> getProjectVisit(VisualizationPo po) {
       Map<String, Object> result = new HashMap<>();
        List<Object> resultList = new ArrayList<>();
        List<String> time = (List<String>) getTime(po,true);
        System.out.println(time);
        result.put("xdata",time);
        //浏览量
        List<Long> countList = new ArrayList<>();
        // 访问量
        List<Long> visitList = new ArrayList<>();
        if (!po.getType().equals("day")){
            for (String datum : time) {
                Map<String,Long> map = new HashMap<>();
                LocalDateTime startTime = LocalDateTime.parse(datum+"-01 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                LocalDate endDate = LocalDate.parse(datum+"-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                LocalDateTime endTime = LocalDateTime.parse(endDate.with(TemporalAdjusters.lastDayOfMonth())+" 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                map=prejectMapper.getProjectVisit(startTime,endTime);
                countList.add(map.get("count"));
                visitList.add(map.get("visit"));
            }
        }else {
            for (String datum : time) {
                Map<String,Long> map = new HashMap<>();
                LocalDateTime startTime = LocalDateTime.parse(datum+" 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                LocalDateTime endTime = LocalDateTime.parse(datum+" 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                map=prejectMapper.getProjectVisit(startTime,endTime);
                countList.add(map.get("count"));
                visitList.add(map.get("visit"));
            }
        }
        HashMap<String, Object> mapCount = new HashMap<>();
        mapCount.put("name","浏览量");
        mapCount.put("data",countList);
        HashMap<String, Object> mapVisit = new HashMap<>();
        mapVisit.put("name","访问量");
        mapVisit.put("data",visitList);
        resultList.add(mapCount);
        resultList.add(mapVisit);
        result.put("result",resultList);
        return result;
    }




}
